package com.geostar.constructionland.analyse.service;

import com.geostar.constructionland.analyse.entity.HttpResult;
import com.geostar.constructionland.common.util.CpdetectorEncoding;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author yelll
 * @since 2020-5-28 15:19
 **/
@Component
@Slf4j
public class HttpAPIService {
    @Autowired
    private CloseableHttpClient httpClient;
    @Autowired
    private RequestConfig config;

    /**
     * 不带参数的get请求，如果状态码为200，则返回body，如果不为200，则返回null
     *
     * @param url
     * @return
     * @throws Exception
     */
    public String doGet(String url) throws Exception {
        // 声明 http get 请求
        HttpGet httpGet = new HttpGet(url);

        // 装载配置信息
        httpGet.setConfig(config);

        // 发起请求
        CloseableHttpResponse response = this.httpClient.execute(httpGet);

        // 判断状态码是否为200
        if (response.getStatusLine().getStatusCode() == 200) {
            // 返回响应体的内容
            return EntityUtils.toString(response.getEntity(), "UTF-8");
        }
        return null;
    }

    /**
     * 带参数的get请求，如果状态码为200，则返回body，如果不为200，则返回null
     *
     * @param url
     * @return
     * @throws Exception
     */
    public String doGet(String url, Map<String, Object> map) throws Exception {
        URIBuilder uriBuilder = new URIBuilder(url);

        if (map != null) {
            // 遍历map,拼接请求参数
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());
            }
        }

        // 调用不带参数的get请求
        return this.doGet(uriBuilder.build().toString());

    }

    /**
     * 带参数的post请求
     *
     * @param url
     * @param map
     * @return
     * @throws Exception
     */
    public HttpResult doPost(String url, Map<String, Object> map) throws Exception {
        // 声明httpPost请求
        HttpPost httpPost = new HttpPost(url);
        // 加入配置信息
        httpPost.setConfig(config);

        // 判断map是否为空，不为空则进行遍历，封装from表单对象
        if (map != null) {
            List<NameValuePair> list = new ArrayList<NameValuePair>();
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                list.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
            }
            // 构造from表单对象
            UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(list, "UTF-8");

            // 把表单放到post里
            httpPost.setEntity(urlEncodedFormEntity);
        }
        // 发起请求
        CloseableHttpResponse response = null;

        int retryTime = 2;
        while(retryTime>0) {
            retryTime--;
            try {
                response = httpClient.execute(httpPost);
            } catch (Exception e) {
                e.printStackTrace();
                if(retryTime == 0){
                    throw e;
                }else {
                    continue;
                }
            }
            break;
        }
        int responseStatus = response.getStatusLine().getStatusCode();
        String responseEntity = EntityUtils.toString(response.getEntity(), "UTF-8");

        try {
            if (response != null) {
                response.close();
            }
        } catch (Exception e) {
            throw e;
        } finally {
            httpPost.abort();
        }

        return new HttpResult(responseStatus, responseEntity);
    }

    /**
     * 不带参数post请求
     *
     * @param url
     * @return
     * @throws Exception
     */
    public HttpResult doPost(String url) throws Exception {
        return this.doPost(url, null);
    }

    /**
     * Json格式参数POST请求
     *
     * @param url
     * @param json
     * @return
     * @throws Exception
     */
    public HttpResult doPostByJsonParam(String url, String json) throws Exception {
        // 声明httpPost请求
        HttpPost httpPost = new HttpPost(url);
        // 加入配置信息
        httpPost.setConfig(config);
        httpPost.setHeader("Content-type", "application/json");
        StringEntity se = new StringEntity(json, "utf-8");
        se.setContentEncoding("UTF-8");
        httpPost.setEntity(se);
        CloseableHttpResponse response = this.httpClient.execute(httpPost);
        return new HttpResult(response.getStatusLine().getStatusCode(), EntityUtils.toString(
                response.getEntity(), "UTF-8"));
    }

    /**
     * 下载文件
     *
     * @param url
     * @param filePath
     * @return
     * @throws Exception
     */
    public String downloadFile(String url, String filePath) throws Exception {
        HttpGet httpget = new HttpGet(url);
        HttpResponse response = this.httpClient.execute(httpget);
        HttpEntity entity = response.getEntity();
        InputStream is = entity.getContent();
        File file = new File(filePath);
        file.getParentFile().mkdirs();
        FileOutputStream fileout = new FileOutputStream(file);
        /**
         * 根据实际运行效果 设置缓冲区大小
         */
        byte[] buffer = new byte[10240];
        int ch = 0;
        while ((ch = is.read(buffer)) != -1) {
            fileout.write(buffer, 0, ch);
        }
        is.close();
        fileout.flush();
        fileout.close();
        return filePath;
    }

    /**
     * 下载文件内容
     *
     * @param url
     * @return
     * @throws Exception
     */
    public String downloadFileForContent(String url) throws Exception {
        HttpGet httpget = new HttpGet(url);
        HttpResponse response = this.httpClient.execute(httpget);
        HttpEntity entity = response.getEntity();
        InputStream inputStream = entity.getContent();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buffer = new byte[10240];
        int n;
        while ((n = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, n);
        }
        byte[] bytes = bos.toByteArray();
        CpdetectorEncoding cpEncoding = new CpdetectorEncoding();
        /**获取文件编码*/
        Charset charsetName = cpEncoding.getFastEncoding(bytes);
        if (charsetName.name().equals("x-EUC-TW")) {
            charsetName = Charset.forName("GBK");
        }
        String result = new String(bytes, charsetName);
        return result;
    }
}